﻿using System;
using System.Linq;
using System.Reflection;
using Se.Framework.Common.Extentions;

namespace Se.Framework.Common.ObjectRegistrySupport
{
    public static class ObjectRegistryExtentions
    {
        public static void RegisterObjectFromAssembly(this IObjectRegistry registry, Assembly assembly, Func<Type, bool> registerCondition)
        {
            foreach (var typeToRegister in assembly.GetTypes().Where(registerCondition))
            {
                var attr = typeToRegister.Attribute<ObjectLifetimeAttribute>();
                if (attr != null && attr.TypeTo != null)
                {
                    if (attr.TypeTo.IsAssignableFrom(typeToRegister))
                        registry.RegisterType(typeToRegister, attr.TypeTo);
                    else
                    {
                        throw new InvalidOperationException(string.Format("Type {0} cannot be assigned from type {1}", attr.TypeTo, typeToRegister));
                    }
                }
                else
                {
                    registry.RegisterType(typeToRegister);
                }

            }
        }

        public static void RegisterObjectFromCurrentAssemby(this IObjectRegistry registry, Func<Type, bool> registerCondition)
        {
            registry.RegisterObjectFromAssembly(Assembly.GetCallingAssembly(), registerCondition);
        }
    }
}
